package com.chaofan.messagebook.web;

import com.chaofan.messagebook.bean.R;
import com.chaofan.messagebook.config.MyBatis;
import com.chaofan.messagebook.entity.Message;
import com.chaofan.messagebook.mapper.MessageMapper;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.ws.rs.*;
import org.apache.ibatis.session.SqlSession;

import java.io.Serial;
import java.io.Serializable;
import java.util.List;

/**
 * @author 李超凡
 * @since 2022/4/18 23:15
 */
@Path("/message")
public class MessageResource implements Serializable {

    @Serial
    private static final long serialVersionUID = 5360472464704858597L;
    @Inject
    private MyBatis myBatis;

    @GET
    @Produces("application/json")
    @Path("/{page}/{size}")
    public String query(@PathParam("page") Integer page, @PathParam("size") Integer size) {
        try (SqlSession session = myBatis.getSession()) {
            MessageMapper mapper = session.getMapper(MessageMapper.class);
            List<Message> messages = mapper.queryByPage(page, size);
            return R.success("查询成功", messages);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @POST
    @Produces("application/json")
    public String add(@Valid Message message) {
        try (SqlSession session = myBatis.getSession()) {
            MessageMapper mapper = session.getMapper(MessageMapper.class);
            int result = mapper.insert(message);
            if (result == 1) return R.success("新增成功");
            return R.fail();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @DELETE
    @Produces("application/json")
    @Path("/{id}")
    public String delete(@PathParam("id") Integer id) {
        try (SqlSession session = myBatis.getSession()) {
            MessageMapper mapper = session.getMapper(MessageMapper.class);
            int result = mapper.deleteById(id);
            if (result == 1) return R.success("删除成功");
            return R.fail();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }
}
